package isanfeng.tuxiaoer.pattern.structural.proxy.dynamicproxy;

import isanfeng.tuxiaoer.pattern.structural.proxy.Order;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author 李红辉
 * @version 1.0
 * @date 2019/10/14 11:30
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private Object target;

    public OrderServiceDynamicProxy(Object target) {
        this.target = target;
    }

    public Object bind() {
        Class cls = target.getClass();
        return Proxy.newProxyInstance(cls.getClassLoader(),  cls.getInterfaces(), this);
    }

    /**
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object argObject = args[0];
        beforeMethod(argObject);
        Object object = method.invoke(target, args);
        afterMethod();
        return object;
    }

    private void beforeMethod(Object argObject) {
        if (!(argObject instanceof Order)) {
            return;
        }

        System.out.println("动态代理， before" + argObject);
    }

    private void afterMethod() {
        System.out.println("动态代理， after");
    }
}
